package com.situ.web.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String fileName = req.getParameter("fileName");//a.mp4
		System.out.println(fileName);
	     //获得文件的绝对路径
	     String filePath = getServletContext().getRealPath("/download/" + fileName);
	     //设置文件的MIME类型
	     String contentType = getServletContext().getMimeType(fileName);
	     System.out.println(contentType);// text/html   text/plain   image/png
	     resp.setContentType(contentType);
	     //设置响应头Content-Disposition，告诉浏览器以附件形式下载，而不是解析展示
	     resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		InputStream inputStream = new FileInputStream(filePath);
		ServletOutputStream outputStream = resp.getOutputStream();
		byte[] buffer = new byte[1024];
	     int length = 0;
	     while ((length = inputStream.read(buffer)) != -1) {
	        outputStream.write(buffer, 0, length);
	     }
	     outputStream.close();
	     inputStream.close();
	}
}
